package unei

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.concurrent.locks.ReadWriteLock
import java.util.concurrent.locks.ReentrantReadWriteLock
import java.util.Date

/**
 * 当加读锁时，其他线程无法写入，但是可以读取数据，当加写锁时，其他线程无法读取或写入
 * Created by sunlei on 2015/8/27.
 */
ReadWriteLock rwLock=new ReentrantReadWriteLock()
for(int i=0;i<10;i++) {
    new Thread() {
        @Override
        void run() {
            try {
                rwLock.writeLock().lock()
                println Thread.currentThread().getId()+"-write lock..."+(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME))
                Thread.sleep(2000)
            } finally{
                rwLock.writeLock().unlock()
            }
        }
    }.start()

    new Thread() {
        @Override
        void run() {
            try {
                rwLock.readLock().lock()
                println Thread.currentThread().getId()+"-read lock..."+(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME))
                Thread.sleep(2000)
            } finally{
                rwLock.readLock().unlock()
            }
        }
    }.start()
}

Thread.sleep(100000)